import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    //Udp协议不包含对方的信息
    private int serverPort;
    private String serverIp;
    private DatagramSocket socket=null;
    public UdpEchoClient(String ip,int port) throws SocketException {
        this.serverIp=ip;
        this.serverPort=port;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            System.out.println("请输入您要发送的信息：");
            if(!scanner.hasNext()){
                break;
            }
            String request=scanner.next();
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            DatagramPacket responsePacket=new DatagramPacket(new byte[4048],4048);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("192.168.137.1",8776);
        client.start();
    }
}
